<template>
  <view class="components-container" v-show="isVisible">
    <view :style="{ marginTop: completeSafeHeight + 'px' }">
      <view class="top">
        <span class="title">你有{{ list.length }}个指派单,请及时处理!</span>
        <span class="tis">请及时选择收到或拒绝派单</span>
      </view>
      <view class="list">
        <delivery-order
          class="delivery-order"
          v-for="deliveryOrder in list"
          :key="deliveryOrder.id"
          :delivery-order="deliveryOrder"
        >
          <template #control>
            <view class="control">
              <view class="button reject" @click="rejectDeliveryOrder(deliveryOrder.id)"
                >拒绝({{ deliveryOrder.lockTime }})</view
              >
              <view class="button ok" @click="acceptSystemDispatchDeliveryOrder(deliveryOrder.id)">收到</view>
            </view>
          </template>
        </delivery-order>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import $store from '@/store'
import webSocketWrapper from '@/utils/ws'
import DeliveryOrder from '../components/delivery-order/index.vue'
import { SystemDispatchNearbyDeliveryOrder } from '@/types/response/delivery-order'
import { ref, computed, watch } from 'vue'
import { countdownEventHandler } from '@/utils/countdownEventHandler'
import $API from '@/api'
import { $modal } from '@/plugins'
import { RiderWorkState } from '@/enum'
const { completeSafeHeight } = $store.app.getSystemParam()

const { put, createListener, close, stateAssociation } = webSocketWrapper('/rider/rider', {
  token: $store.user.tokens.getAccessToken()
})
const list = ref<Array<SystemDispatchNearbyDeliveryOrder>>([])
const isVisible = computed(() => list.value.length > 0)
const riderWSRequest = {
  putGeo(geo: { longitude: number; latitude: number }) {
    put('/put-geo', geo)
  },
  rejectDeliveryOrder(deliveryOrderId: number) {
    put(`/reject-delivery-order/${deliveryOrderId}`)
  },
  removeGeo() {
    put(`/remove-rider-geo`)
  }
}
const riderWSListener = {
  newDeliveryOrderEvent: createListener('/delivery-order')
}
const riderInfo = $store.user.info
// 当关闭骑手状态与ws
watch(
  () => riderInfo.value.workStatus,
  (workStatus) => (stateAssociation.value = workStatus === RiderWorkState.ONLINE)
)
// 当geo刷新时，更新服务端骑手的geo信息
$store.user.geo.addOnRefreshListener((geoInfo) => {
  // 看骑手是否在线，不在线就不更新
  if (riderInfo.value.workStatus === RiderWorkState.OFFLINE) return
  riderWSRequest.putGeo(geoInfo)
})
// 移除消息
function timeoutRemoveMessage(deliveryOrderId: number) {
  for (let [index, item] of list.value.entries()) {
    if (item.id == deliveryOrderId) {
      list.value.splice(index, 1)
    }
  }
}
// 监听新订单事件
riderWSListener.newDeliveryOrderEvent.onListener((message: SystemDispatchNearbyDeliveryOrder) => {
  // 处理新订单
  list.value.push(message)
  message.lockTime = ref(message.lockTime)
  countdownEventHandler(message.lockTime, () => timeoutRemoveMessage(message.id))
})
// 手动点击拒绝
function rejectDeliveryOrder(deliveryOrderId: number) {
  riderWSRequest.rejectDeliveryOrder(deliveryOrderId)
  // 从列表中删除
  setTimeout(() => timeoutRemoveMessage(deliveryOrderId), 200)
}
async function acceptSystemDispatchDeliveryOrder(deliveryOrderId: number) {
  const result = await $API.deliveryOrder.acceptSystemDispatchDeliveryOrder(deliveryOrderId)
  if (result.success) {
    $modal.toastSuccessMsg('接单成功！')
    // 触发骑手接新单事件
    $store.order.onReceivingNewOrder.emit()
  } else {
    $modal.toastMsg('订单已超时未接单！')
  }
  timeoutRemoveMessage(deliveryOrderId)
}
// 监听骑手状态的改变，当变为离线时，移除骑手geo
watch(
  () => $store.user.info.value.workStatus,
  (workStatus) => {
    if (workStatus == RiderWorkState.OFFLINE) {
      // 发送请求移除骑手的geo信息
      $API.rider.removeRiderGeo()
    }
  }
)
</script>

<style scoped lang="scss">
.components-container {
  position: fixed;
  z-index: 10000;
  padding: 0 25rpx;
  background-color: #f5f5f5;
  inset: 0;
  box-sizing: border-box;

  .top {
    display: flex;
    flex-direction: column;

    .title {
      font-size: 45rpx;
      font-weight: 700;
      line-height: 70rpx;
    }

    .tis {
      font-size: 28rpx;
      color: #494949;
    }
  }

  .list {
    .delivery-order {
      .control {
        display: flex;
        justify-content: space-around;

        .button {
          width: 42%;
          font-size: 30rpx;
          font-weight: 500;
          border: 1rpx solid #676767;
          border-radius: 10rpx;
          text-align: center;
          line-height: 35px;
        }

        .ok {
          $ok-bg-color: rgb(255 223 13);

          border: 1rpx solid $ok-bg-color;
          background-color: $ok-bg-color;
        }
      }
    }
  }
}
</style>
